<template>
  <div class="app-container">

 <!--工具栏-->
    <div class="head-container">

      <!-- 搜索 -->
      <el-form :model="queryParams" ref="queryForm"  :inline="true">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="角色状态"
            clearable
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>


      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-permission="['ROLE_admin','roles:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-permission="['ROLE_admin','roles:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-permission="['ROLE_admin','roles:del']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-permission="['ROLE_admin','role:export']"
          >导出</el-button>
        </el-col>

      </el-row>



    </div>

  <!-- 显示表格以及分页条 -->
   <el-card class="box-card" shadow="never">

     <div slot="header" class="clearfix">
       <span class="role-span">角色列表</span>
     </div>

     <el-table ref="table" v-loading="loading" highlight-current-row style="width: 100%;" :data="dataTable"
      @selection-change="selectionChangeHandler"      >
       <el-table-column  type="selection" width="55" />
       <el-table-column  prop="roleName" label="名称" />
       <el-table-column  prop="roleKey" label="角色权限" />
       <el-table-column  label="状态" >
         <template slot-scope="scope">
           <el-tag  v-if="scope.row.status===0" type="success" effect="dark">启用</el-tag>
           <el-tag  v-else type="danger" effect="dark">禁用</el-tag>
         </template>
       </el-table-column>
       <el-table-column :show-overflow-tooltip="true" width="135px" prop="createTime" label="创建日期"></el-table-column>
       <el-table-column v-permission="['admin','roles:edit','roles:del']" label="操作" width="130px" align="center" fixed="right">
         <template slot-scope="scope">
           <el-button v-permission="['admin','roles:edit']"  size="mini" type="primary" icon="el-icon-edit"  />
           <el-button v-permission="['admin','roles:del']"  size="mini" type="danger" icon="el-icon-delete"  />

         </template>
       </el-table-column>
     </el-table>

     <!--分页组件-->
     <el-pagination
       :page-size.sync="queryParams.pageSize"
       :current-page.sync="queryParams.pageNumber"
       :total="total"
       style="margin-top: 8px;"
       layout="total, prev, pager, next, sizes"
       @size-change="sizeChangeHandler"
       @current-change="pageChangeHandler"
     />

   </el-card>





  <!-- 新增/修改对话框 -->
    <el-dialog append-to-body :close-on-click-modal="false" :visible.sync="dialogVisible " :title="title" width="520px">
      <el-form ref="form"  :model="editForm" :rules="rules" size="small" label-width="80px">

        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"  />
        </el-form-item>

        <el-form-item label="角色权限" prop="roleKey">
          <el-input v-model="editForm.roleKey" />
        </el-form-item>

		    <el-form-item label="状态" prop="status">

            <el-radio-group v-model="editForm.status">
              <el-radio v-for="item in statusOptions" :key="item.dictValue"  :label="item.dictValue">{{item.dictLabel}}</el-radio>
            </el-radio-group>
        </el-form-item>

        <el-form-item label="菜单权限">
         <el-tree
            :data="menuData"
            show-checkbox
            node-key="menuId"
            ref="menuTree"
            highlight-current
            :check-strictly="checkStrictly"
            :props="defaultProps">
          </el-tree>

        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialogVisible=false">取消</el-button>
        <el-button  type="primary"  @click="saveForm">确认</el-button>
      </div>
    </el-dialog>





  </div>
</template>

<script>
import {getData, save} from  '@/api/system/role.js'
import {getMenusTree, ownMenuByRoleId} from  '@/api/system/menu.js'
import {getByDictId} from  '@/api/system/dictDetail.js'

export default {
  name: "Role",
  data() {
    return {
      // 编辑对话框的属性
      dialogVisible: false,
      title: '新增角色',
      editForm: {
        roleName: undefined,
        roleKey: undefined,
        status: '0'
      },
      // 加载所有菜单
      menuData: [],
      //树型节点父子不相关系（不要联动）
      checkStrictly: false,
      defaultProps: {
         label: 'menuName',
         children: 'children'
      },
      // 数据验证
      rules : {
        roleName: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: '该值不能为空', trigger: 'blur' }
        ]
      },
      // 当前选中的哪几行
      selections: [],
      // 修改按钮禁用
      single: true,
      // 删除按钮禁用
      multiple :true,
      // 状态集合数据
      statusOptions: [],
       // 日期范围
      dateRange: [],
      queryParams: {
        roleName: undefined,
        status: undefined,
        pageSize: 5,
        pageNumber: 1
      },
      // 分页相关的对象
      loading: true,
      // 分页表格数据
      dataTable: [],
      // 分页总记录数
      total:0
    }
  },
  created() {
    // 加载查询状态条件
    this.fetchDictDetails()
    // 加载角色数据
    this.fetchRoleData()
    // 加载菜单
    this.fetchMenuTree()
  },
  methods: {
    // 加载状态数据
    fetchDictDetails(){
      getByDictId(17).then( resp => {
        this.statusOptions = resp.data
      })
    },
    // 重置按钮
    resetQuery () {

    },
    // 查询按钮
    handleQuery() {
      // 删除里面的数据
      delete this.queryParams.startTime
      delete this.queryParams.endTime

      if(this.dateRange && this.dateRange.length==2) {
        this.queryParams.startTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      }

      this.queryParams.pageNumber = 1

      this.fetchRoleData()

    },
    // 导出
    handleExport() {

    },
    // 新增
    handleAdd() {
      // 显示对话框(必须写在第一行)
      this.dialogVisible =true
      // 清空数据、清除验证样式
      this.restForm()

      // 更改标题
      this.title = '添加角色'

    },
    //修改
    handleUpdate (){
      // 显示对话框(必须写在第一行)
      this.dialogVisible =true
      // 清空数据、清除验证样式
      this.restForm()
      // 设定父子关系不要联动
      this.checkStrictly = true

      // 回填充数据
      this.$nextTick( () => {
        this.updateFillData('roleId')

        // -----设定这个角色拥有菜单有哪些（勾选上）---  ajax 查询 异步
        ownMenuByRoleId(this.editForm.roleId).then( resp => {
          this.$refs.menuTree.setCheckedKeys( resp.data)
          // 设定父子关系要联动
          this.checkStrictly = false

        })

      })

      // 更改标题
      this.title = '修改角色'
    },
    // 清空数据
    restForm() {
      //删除主键
      if(this.editForm.hasOwnProperty("roleId")){
        // delete this.editForm.roleId  非常粗暴
        this.$delete( this.editForm, "roleId")  // 建议这样做
      }

      this.editForm.roleName = undefined
      this.editForm.roleKey =undefined
      this.editForm.status = '0'
     // 设定父子关系要联动
       this.checkStrictly = false



      // vue的异步通知机制 (当节点更新完成以后，再做回调函数)
      this.$nextTick( () => {
         // 设定所有菜单未选择 (已经加载到 dom 节点以后，才生效)
          this.$refs.menuTree.setCheckedKeys([])
          //清除验证样式
          this.$refs['form'].resetFields();
      })

    },
    // 删除
    handleDelete () {

    },
    // 表格当前选择了多少行
    selectionChangeHandler (vals) {
      this.selections =vals
      this.multiple = true
      this.single =true
      if( vals && vals.length>0){
         this.multiple = false
         this.single = !(vals.length ===1)
      }
    },
    // 每页显示几笔大小发生变化
    sizeChangeHandler ( val) {
      this.queryParams.pageNumber =1
      this.queryParams.pageSize= val
      this.fetchRoleData()
    },
    // 当前第几页发生变化
    pageChangeHandler (val) {
      this.queryParams.pageNumber= val
      this.fetchRoleData()
    },
    // 加载角色数据
    fetchRoleData (){
      // 要显示动画
      this.loading = true

      getData(this.queryParams).then( resp => {
        this.dataTable = resp.data.data
        this.total = resp.data.total
      })
      // 要停止动画
      this.loading = false
    },
    //加载所有菜单
    fetchMenuTree() {
      getMenusTree().then(resp => {
        this.menuData = resp.data
      })
    },
    // 更新回填数据
    updateFillData(primaryKey) {
      // 还原数据初始值 把item 进行对象的深度copy Json转换字符串转换成js对象,  浅cpoy   Object.assign( {},原始对象)
      let  item = JSON.parse(JSON.stringify(this.selections[0]))
      console.log(item)
      //更优方法
      this.$set(this.editForm,primaryKey, item.roleId)

      for(const key in this.editForm){
        // 判断 item是否允许这个属性
        if( item.hasOwnProperty(key)){
          if( key==='status') {
             this.editForm[key] = item[key]+''
          }else {
             this.editForm[key] = item[key]
          }

        }
      }
    },
    // 保存
    saveForm() {
      // 1、判断是否验证通过
      this.$refs['form'].validate((valid) => {
         if (!valid) {
             return false;
         }
         // 保存数据
         this.saveData()
      });
   },
   // 真正保存数据
   saveData() {
     // 收集权限
     // 已勾选的
     let checkedKeys= this.$refs.menuTree.getCheckedKeys()
     // 半勾选的
     let checkedHalfKeys= this.$refs.menuTree.getHalfCheckedKeys()

     let menuIds= checkedHalfKeys.concat(checkedKeys)

     this.$set(this.editForm,"menuIds", menuIds);

     save(this.editForm).then(resp => {
        this.dialogVisible =false
        this.fetchRoleData()
     })


   }

  }

};
</script>
